<!--动作 延时 -->
<template>
  <el-dialog
    title="提示"
    v-model="dialogVisible"
    style="width: 40%; height: 100%; float: right; margin: 0"
    :close-on-click-modal="false"
    :showClose="false"
    :before-close="Cancel"
  >
    <!-- 头部 -->
    <template #title>
      <!-- 这里添加您希望在左上角放置的内容，例如关闭按钮 -->
      <span>
        <i class="el-icon-close" @click="dialogVisible = false" style="cursor: pointer"></i>
      </span>
      <span> 添加延时动作 </span>
    </template>
    <el-form label-position="top">
      <!-- 上面两行input -->
      <div style="display: flex">
        <!-- 设备选择 -->
        <el-form-item label="设备选择" style="display: inline-block; flex: 1">
          <el-select
            v-model="SelectDevice"
            placeholder="请选择"
            style="width: 100%"
            @change="DeviceChange"
          >
            <el-option
              v-for="item in AxiosOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="选择动作">
        <el-col v-for="(item, index) in executions" :key="index">
          <!-- {{ item }} -->
          <div
            v-if="item.type == 'write' || item.type == 'both'"
            style="display: flex; justify-content: center; align-items: center; margin: 10px"
          >
            <!-- 执行条件的文字显示 -->
            <span style="flex: 1; text-align: center">{{ item.propertyName }}</span>
            <span style="flex: 1; text-align: center">操作</span>
            <span style="flex: 2; text-align: center">
              <el-select
                v-if="item.renderModel === 'select'"
                v-model="item.statusValue"
                class="m-2"
                placeholder="请输入"
              >
                <el-option
                  v-for="item in AutoRendermod2[item.rendermod2]"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
              <span v-else-if="item.renderModel === 'component'">
                <el-select v-model="selectTime" placeholder="请选择">
                  <el-option
                    v-for="item in TimeSelect"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
                <el-time-picker
                  v-if="selectTime === '常量'"
                  style="width: 100%"
                  v-model="timeR"
                  format="HH:mm:ss"
                  value-format="H:m:s"
                />
                <!-- <el-input
                  v-if="selectTime === '变量'"
                  v-model="handleTime"
                  placeholder="请输入"
                ></el-input> -->
                <el-cascader
                  v-if="selectTime === '变量'"
                  style="width: 100%"
                  v-model="handleTime"
                  :options="SystemVariable"
                  :props="{
                    label: 'name',
                    value: 'id',
                    expandTrigger: 'hover'
                  }"
                  @change="handlechange(handleTime)"
                />
              </span>
              <span v-if="item.renderModel === 'input'">
                <el-input v-model="item.statusValue" placeholder="单位为毫秒"></el-input>
              </span>
            </span>

            <span style="flex: 1; text-align: center">
              <el-link @click="DeleteFilled(index, 1)" :underline="false" style="margin-left: 5%"
                ><el-icon><DeleteFilled /></el-icon
              ></el-link>
            </span>
          </div>
        </el-col>
        <!-- <div>定时器使用示例：延时30秒为（00:00:30），延时一个小时为（01:00:00）</div> -->
      </el-form-item>
    </el-form>

    <!-- 底部 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button v-if="showDelete" type="danger" @click="DeleteActions">删除</el-button>
        <el-button @click="Cancel">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
        <!-- <el-button @click="loginaa">显示设备</el-button> -->
      </span>
    </template>
  </el-dialog>
</template>
  
  <script>
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import AutoRendermod2JSON from '../../../MyJson/AutoRendermod2.json'
import until from '../../../until/csUntil/deviceUtils'
import { ElMessage } from 'element-plus'
import { ElTimePicker } from 'element-plus'
import { v4 as uuidv4 } from 'uuid'

export default {
  setup(_, { emit }) {
    //
    const timeR = ref('00:00:00')
    // 导入 自动化模板2
    const AutoRendermod2 = ref(AutoRendermod2JSON.template)
    // dialog的关闭显示
    const dialogVisible = ref(false)
    //  select  选择设备的值
    const SelectDevice = ref('')
    // vuex导入
    const store = useStore()
    // 假数据
    const AxiosOptions = ref(null)
    // vuex 导入 设备
    const device = ref(store.state.beforeAllDevice)
    // vuex 设备类型
    const deviceTypeStr = ref(store.state.deviceTypeStr)
    // 动作
    const executions = ref([])

    // 设备id
    const id = ref(null)
    // 设备名称
    const deviceName = ref(null)
    // 变量 绑定的值
    const handleTime = ref(null)
    // select 选择的值 变量 OR 常量
    const selectTime = ref(null)
    //  系统变量
    const SystemVariable = ref(null)
    const TimeSelect = ref([
      { name: '常量', value: '常量' },
      { name: '变量', value: '变量' }
    ])
    const showDelete = ref(false)
    //
    //
    //
    //
    //
    //
    //
    //
    // 打开dialog
    const openmyDialog = () => {
      dialogVisible.value = true
      tiemvalue.value = ''
      // const res = store.state.beforeAllDevice
      // SystemVariable.value = res.filter((item) => item.SystemVariableType === 'NUMBER')
    }

    const closeTime = () => {}
    // 选中设备的值
    const DeviceChange = (event) => {
      executions.value = []
      id.value = event
      const res = AxiosOptions.value.find((item) => item.id === event)

      if (res) {
        deviceName.value = res.name
        const result = JSON.parse(JSON.stringify(res))
        executions.value = result.values

        executions.value.forEach((item) => {
          if (item.propertyName === '开关') {
            item.statusValue = '开'
          }
          if (item.propertyName === '计数器') {
            item.statusValue = '0'
          }
          if (item.statusName === 'referenceBenchmark' && item.statusval) {
            // 计算小时
            const hours = Math.floor(item.statusval / 3600)
            // 计算剩余的分钟
            const minutes = Math.floor((item.statusval % 3600) / 60)
            // 计算剩余的秒
            const remainingSeconds = Math.floor(item.statusval % 60)

            // 格式化为两位数的字符串，如果需要的话
            const formattedHours = String(hours).padStart(2, '0')
            const formattedMinutes = String(minutes).padStart(2, '0')
            const formattedSeconds = String(remainingSeconds).padStart(2, '0')

            // 返回格式化后的字符串
            timeR.value = `${formattedHours}:${formattedMinutes}:${formattedSeconds}`
            selectTime.value = '常量'
          }
        })
      }
    }
    // 删除
    const DeleteFilled = (index) => {
      executions.value.splice(index, 1)
    }
    // 确定后输出表单
    const submit = () => {
      let statusType1 = ''
      if (selectTime.value === '常量') {
        timeStringToSeconds(timeR.value)
        handleTime.value = null
        statusType1 = 'AUTO_SCHED_EXECUTION_TIMER_NUMBER'
      }
      if (selectTime.value === '变量') {
        timeR.value = '00:00:00'
        statusType1 = 'AUTO_SCHED_EXECUTION_TIMER_DEVICE_VARIABLE'
      }
      const uuid = uuidv4()
      let result = []
      executions.value.map((item) => {
        if (item.statusValue) {
          let res = {
            id: uuid,
            executionType: 'AUTO_SCHED_EXECUTION_TYPE_DEVICE',
            deviceId: id.value,
            statusName: item.statusName,
            statusValue: item.statusValue,
            deviceName: deviceName.value,
            rendermod1: item.rendermod1,
            rendermod2: item.rendermod2,
            tiemvalue: tiemvalue.value,
            selectTime: selectTime.value,
            type: item.type,
            renderModel: item.renderModel,
            name: item.propertyName,
            propertyName: item.propertyName,
            Change: 'TimeTaskActions',
            showinfo: showinfo.value
          }
          if (item.propertyName === '定时器时长') {
            res.statusType = statusType1
            result.push(res)
          } else {
            result.push(res)
          }
        }
      })
      if (result.length) {
        emit('executions', result)
        Cancel()
      } else {
        ElMessage.error('请选择设备')
      }
    }
    // 取消
    const Cancel = () => {
      SelectDevice.value = ''
      executions.value = []
      dialogVisible.value = false
      timeR.value = '00:00:00'
      selectTime.value = ''
      handleTime.value = ''
      tiemvalue.value = ''
      showinfo.value = []
      showDelete.value = false
    }

    // 转秒
    const timeStringToSeconds = (timeString) => {
      const [hours, minutes, seconds] = timeString.split(':').map(Number)
      const res = hours * 3600 + minutes * 60 + seconds
      executions.value.forEach((item) => {
        if (item.renderModel === 'component') {
          item.statusValue = String(res)
        }
      })
    }
    // 测试
    const loginaa = () => {}
    onMounted(() => {
      // AxiosOptions.value = JSON.parse(JSON.stringify(res))
      // store.state.beforeAllDevice
      SystemVariable.value = []
      const res = store.state.beforeAllDevice
      res.forEach((item) => {
        if (item.id === '1234567890') {
          item.children = item.property
          item.children.forEach((e) => {
            e.id = e.statusName
            e.name = e.propertyName
          })
        }
      })
      // SystemVariable.value = res.filter((item) => {
      //   return
      // })
      res.forEach((item) => {
        if (item.SystemVariableType === 'NUMBER' || item.id === '1234567890') {
          SystemVariable.value.push(item)
        }
      })
    })

    const filterList = (data) => {
      dialogVisible.value = true
      const dds = []
      data.map((item) => {
        item.map((event) => {
          dds.push(event.deviceName)
        })
      })

      const listDvcAndDvcVer = window.api.listDvcAndDvcVer()

      const MyfilterList = JSON.parse(listDvcAndDvcVer)

      const res = MyfilterList.filter(
        (item) => item.isVirtual === 'IS_VIRTUAL' && item.DevicetypeValue === 1001
      )

      if (res) {
        const result = JSON.parse(JSON.stringify(res))

        // result.forEach((item) => {
        //   if (dds.includes(item.name)) {
        //     item.disabled = true
        //   }
        // })

        AxiosOptions.value = result
      }
    }

    const tiemvalue = ref('')
    const showinfo = ref([])
    const handlechange = (data) => {
      showinfo.value = []
      showinfo.value = data
      if (data.length === 2) {
        SystemVariable.value.forEach((item) => {
          if (item.id === data[0]) {
            item.children.forEach((e) => {
              if (e.statusName === data[1]) {
                tiemvalue.value = e.propertyName
              }
            })
          }
        })

        executions.value.forEach((item) => {
          if (item.renderModel === 'component') {
            item.statusValue = `{${data[0]}.${data[1]}}`
          }
        })
      }
      if (data.length === 1) {
        SystemVariable.value.forEach((item) => {
          if (item.id === data[0]) {
            tiemvalue.value = item.name
          }
        })

        executions.value.forEach((item) => {
          if (item.renderModel === 'component') {
            item.statusValue = data[0]
          }
        })
      }
    }
    // 删除
    const DeleteActions = () => {
      emit('DeleteActions')
      Cancel()
    }
    return {
      showDelete,
      AutoRendermod2,
      deviceTypeStr,
      executions,
      dialogVisible,
      SelectDevice,
      AxiosOptions,
      device,
      id,
      deviceName,
      timeR,
      TimeSelect,
      selectTime,
      handleTime,
      SystemVariable,
      tiemvalue,
      showinfo,
      closeTime,
      filterList,
      openmyDialog,
      submit,
      DeviceChange,
      DeleteFilled,
      Cancel,
      timeStringToSeconds,
      handlechange,
      loginaa,
      DeleteActions
    }
  }
}
</script>
  
  <style lang="less" scoped>
.myCascader {
  display: flex;
}
::v-deep .el-popper {
  width: 500px;
}
</style>
  